﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Pasta.Medio.Concrete;

namespace Pasta.Medio.Controls
{
	public class TabWizard : TabControl
	{
		public TabWizard()
		{
			ShowTabs = false;
		}

		protected override void WndProc(ref Message m)
		{
			if (m.Msg == 0x1328 && !DesignMode && !ShowTabs)
				m.Result = (IntPtr)1;
			else
				base.WndProc(ref m);
		}

		public bool Remove(int index)
		{
			bool success = false;
			if (index >= 0 && index < TabPages.Count)
			{
				TabPages.RemoveAt(index);
				success = true;
			}
			return success;
		}

		public bool ShowTabs { get; set; }

		public void SelectTab(string key)
		{
			int index = TabPages.IndexOfKey(key);
			if( index >= 0 )
			{
				SelectedIndex = index;
			}
		}

		protected override void OnSelecting(TabControlCancelEventArgs e)
		{
			TabBase tab = e.TabPage.Controls[0] as TabBase;
			if( tab != null )
			{
				tab.RefreshPage();
			}
			base.OnSelecting(e);
		}

		public TabBase GetTab( string key )
		{
			TabBase page = null;
			int index = TabPages.IndexOfKey(key);
			if (index >= 0)
			{
				page = TabPages[index].Controls[0] as TabBase;
			}
			return page;
		}

		public TabBase InsertTab<TPage>(int position, string key, string text = null) where TPage : TabBase
		{
			text = text ?? key;

			TabBase tab = GetTab(key);
			if (tab == null)
			{
				try
				{
					tab = Activator.CreateInstance(typeof(TPage)) as TabBase;
					tab.Dock = DockStyle.Fill;
					tab.Name = key;
					TabPage tp = new TabPage(text);
					tp.Name = key;
					tp.BackColor = Color.White;
					tp.Controls.Add(tab);
					if (position >= 0)
						TabPages.Insert(0, tp);
					else
						TabPages.Add(tp);
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
			return tab;
		}

		public TabBase AddTab<TPage>(string key, string text = null) where TPage : TabBase
		{
			return InsertTab<TPage>(-1, key, text);
		}
	}
}
